//
//  HMOAuthViewController.swift
//  WeiboTT
//
//  Created by 王嘉涛 on 2016/11/15.
//  Copyright © 2016年 王嘉涛. All rights reserved.
//

import UIKit
import SVProgressHUD

let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

//OC中有多继承吗? 如果没有,使用什么来替代?  --> 协议
class HMOAuthViewController: UIViewController {
    
    //定义属性
    let webView = UIWebView()
    override func loadView() {
        //自定义根视图
        view = webView
        //指定代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: "", target: self, action: #selector(close))
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "点我让你满足哦", imageName: "", target: self, action: #selector(fillAccount))
        
        
        //设置背景颜色 使用手写代码创建的控制器的背景颜色是透明的
        self.view.backgroundColor = UIColor.white
        //请求授权页面
        loadOauthPage()
        
        //在本类中无法调用分类中的私有方法
        //self.loadAccessToken(code: <#T##String#>)
        //Person().dadoudou()
    }
    
    @objc private func fillAccount() {
        let jsString = "document.getElementById('userId').value = '15102100282', document.getElementById('passwd').value = 'taoge001'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    private func loadOauthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + WB_APPKEY + "&redirect_uri=" + WB_REDIRECTURI
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
    }
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    //在页面关闭的时候 dismiss掉指示器
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
}

//将代理方法抽取到分类中实现, 将模块的功能独立出来,更加好维护
extension HMOAuthViewController: UIWebViewDelegate {
    //MARK: 实现协议方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //一般协议方法返回值为bool类型 如果返回true 就可以正常工作否则就不能够正常工作
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //http://www.itheima.com/?code=99da14a3af1a938d830544d0a013be32
        let urlString = request.url?.absoluteString ?? ""
        //判断urlStirng 中是否包含了特殊的标记吧如果包含就可以截取code
        let flag = "code="
        if urlString.contains(flag) {
            //能够截取code
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            print(code)
            
            //获取了code之后就应该使用code 获取用户的token(访问接口的唯一标识)
            //如果获取了code之后就应该 return false 不加载页面
            HMUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSuccess: Bool) -> () in
                if !isSuccess {
                    //没有成功
                    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
                    return
                }
                
                //请求成功
                print("请求成功")
                //切换根视图控制器  --> 切换根视图控制器 --> 欢迎页面
                UIApplication.shared.keyWindow?.rootViewController = HMWelcomeViewController()
            })
            return false
        }
        
        return true
    }
    
    
}
